<?php
namespace app\manage\controller;

use app\manage\controller\common;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use think\Db;

class BetController extends CommonController{
	/**
	 * 空操作处理
	 */
	public function _empty(){
		return $this->lists();
	}
	/**
	 * 用户资金流水
	 */
	public function financial(){
		if (request()->isAjax()) {
			$param = input('post.');

			//查询条件组装
			$where = array();
			$where[] = array('types','=',1);

			if (isset($param['isUser'])) {
				$where[] = array('types','=',$param['isUser']);
				$pageParam['isUser'] = $param['isUser'];
			}
			//搜索类型
			if(isset($param['search_type']) && $param['search_type'] && isset($param['search_content']) && $param['search_content']){
				switch ($param['search_type']) {
					case 'remarks':
						$where[] = array('remarks','like','%'.$param['search_content'].'%');
						break;
					default:
						$where[] = array($param['search_type'],'=',$param['search_content']);
						break;
				}
			}
			//交易类型
			if(isset($param['trade_type']) && $param['trade_type']){
				$where[] = array('trade_type','=',$param['trade_type']);
			}
			//交易金额
			if(isset($param['price1']) && $param['price1']){
				$where[] = array('trade_amount','>=',$param['price1']);
			}
			//交易金额
			if(isset($param['price2']) && $param['price2']){
				$where[] = array('trade_amount','<=',$param['price2']);
			}
			//时间
			if(isset($param['datetime_range']) && $param['datetime_range']){
				$dateTime = explode(' - ', $param['datetime_range']);
				$where[] = array('trade_time','>=',strtotime($dateTime[0]));
				$where[] = array('trade_time','<=',strtotime($dateTime[1]));
			}else{
				// $todayStart = mktime(0,0,0,date('m'),date('d'),date('Y'));
				// $where[] = array('trade_time','>=',$todayStart);
				// $todayEnd = mktime(23,59,59,date('m'),date('d'),date('Y'));
				// $where[] = array('trade_time','<=',$todayEnd);
			}

			//$count              = model('TradeDetails')->where($where)->count(); // 总记录数
			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'trade_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('TradeDetails')
			->where($where)
			->order($param['sortField'], $param['sortType'])
			->limit($limitOffset, $param['limit'])
			->paginate($param['limit'])
			->toArray();

			//部分元素重新赋值
			$tradeType   = config('custom.transactionType');//交易类型
			$orderColor  = config('manage.color');
			$adminColor  = config('manage.adminColor');
			foreach ($data['data'] as $key => &$value) {
				$value['trade_time']     = date('Y-m-d H:i:s', $value['trade_time']);
				$value['tradeType']      = isset($tradeType[$value['trade_type']])?$tradeType[$value['trade_type']]:'';
				$value['tradeTypeColor'] = isset($adminColor[$value['trade_type']])?$adminColor[$value['trade_type']]:'';
				$value['statusStr']      = config('custom.tradedetailsStatus')[$value['state']];
				$value['statusColor']    = $orderColor[$value['state']];
				$value['front_type_str'] = config('custom.front_type')[$value['front_type']];
				$value['payway_str']     = config('custom.payway')[$value['payway']];
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $data['total'],
				'data'  => $data['data']
			]);
		}

		return view();
	}
	/**
	 * 商户资金流水
	 */
	public function mfinancial(){
		if (request()->isAjax()) {
			$param = input('post.');

			//查询条件组装
			$where = array();
			$where[] = array('types','=',2);

			if (isset($param['isUser'])) {
				$where[] = array('types','=',$param['isUser']);
				$pageParam['isUser'] = $param['isUser'];
			}
			//搜索类型
			if(isset($param['search_type']) && $param['search_type'] && isset($param['search_content']) && $param['search_content']){
				switch ($param['search_type']) {
					case 'remarks':
						$where[] = array('remarks','like','%'.trim($param['search_content']).'%');
						break;
					default:
						$where[] = array($param['search_type'],'=',trim($param['search_content']));
						break;
				}
			}
			//交易类型
			if(isset($param['trade_type']) && $param['trade_type']){
				$where[] = array('trade_type','=',$param['trade_type']);
			}
			//交易金额
			if(isset($param['price1']) && $param['price1']){
				$where[] = array('trade_amount','>=',$param['price1']);
			}
			//交易金额
			if(isset($param['price2']) && $param['price2']){
				$where[] = array('trade_amount','<=',$param['price2']);
			}
			//时间
			if(isset($param['datetime_range']) && $param['datetime_range']){
				$dateTime = explode(' - ', $param['datetime_range']);
				$where[] = array('trade_time','>=',strtotime($dateTime[0]));
				$where[] = array('trade_time','<=',strtotime($dateTime[1]));
			}else{
				$todayStart = mktime(0,0,0,date('m'),date('d'),date('Y'));
				$where[] = array('trade_time','>=',$todayStart);
				$todayEnd = mktime(23,59,59,date('m'),date('d'),date('Y'));
				$where[] = array('trade_time','<=',$todayEnd);
			}

			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'trade_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('TradeDetails')
			->where($where)
			->order($param['sortField'], $param['sortType'])
			->limit($limitOffset, $param['limit'])
			->paginate($param['limit'])
            ->toArray();
			//部分元素重新赋值
			$tradeType   = config('custom.transactionType');//交易类型
			$orderColor  = config('manage.color');
			$adminColor  = config('manage.adminColor');
			foreach ($data['data'] as $key => &$value) {
				$value['trade_time']      = date('Y-m-d H:i:s', $tradeType[$value['trade_time']]);
				$value['tradeType']      = $tradeType[$value['trade_type']];
				$value['tradeTypeColor'] = $adminColor[$value['trade_type']];
				$value['statusStr']      = config('custom.tradedetailsStatus')[$value['state']];
				$value['statusColor']    = $orderColor[$value['state']];
				$value['front_type_str'] = config('custom.front_type')[$value['front_type']];
				$value['payway_str']     = config('custom.payway')[$value['payway']];
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $data['total'],
				'data'  => $data['data']
			]);
		}

		return view('financial');
	}
	/**
	 * 流水详情
	 */
	public function financial_dateils(){
		$data = model('TradeDetails')->financialDateils();

		$this->assign('info',$data);

		return $this->fetch();
	}
	/**
	 * 交易列表
	 * @return [type] [description]
	 */
	public function buytrans(){
		$data = model('UserTransaction')->transAction($bitype=1);//买币
		return view('trans_action', [
			'data' => $data
		]);
	}

	public function selltrans(){
		$data = model('UserTransaction')->transAction($bitype=2);//卖币
		return view('trans_action', [
			'data' => $data
		]);
	}

	//交易详情
	public function transdateils(){

		$data = model('UserTransaction')->transdateils();//卖币

		$this->assign('orderInfo',$data);

		return $this->fetch();
	}

	//交易订单操作
	public function operationtrans(){
		return model('UserTransaction')->operationtrans();
	}

	/**
	 * 回调
	 */
	public function callBack(){
		$id = input('post.id/d');
		$order = model('Order')->where('id', $id)->findOrEmpty();
		if (!$order) return '订单不存在';

		$callBackData = array(
			'uid'              => $order['uid'],
			'merchantId'       => model('Merchant')->where('id', $order['mid'])->value('merchantid'),
			'timestamp'        => $order['timestamp'],
			'signatureMethod'  => 'HmacSHA256',
			'signatureVersion' => 1,
			'orderId'          => $order['orderid'],
			'status'           => 3,
			'jOrderId'         => $order['jorderid'],
			'notifyUrl'        => base64_decode($order['notifyurl']),
			'orderType'        => $order['ordertype'],
			'amount'           => $order['oamount'],
			'currency'         => $order['currency'],
			'actualAmount'     => $order['oactualamount'],
			'fee'              => $order['feeamount'],
			'payWay'           => $order['payway'],
			'payTime'          => $order['paytimes'],
			'jExtra'           => base64_decode($order['jextra']),
			'mkey'             => $order['mkey'],
		);
		model('api/Order')->Callback($callBackData);

		return 1;
	}

	/**
	 * 添加项目
	 * @return [type] [description]
	 */
	public function taskAdd(){
		if (request()->isAjax()) {
            return model('manage/Task')->add();
        }

		$nft_id=request()->param('nft_id',0,'intval');
		$nftInfo=db('nft')->alias('a')->field('a.*,b.username')->join('users b','a.uid=b.id','left')->where(['a.id'=>$nft_id])->find();

        if (empty($nftInfo)){
            return '对应nft未找到:'.$nft_id;
        }
		$taskClass = model('TaskClass')->select()->toArray();
		$userLevel = model('UserGrade')->where('lang','en')->select()->toArray();
		$taskModle = model('taskModel')->select()->toArray();
		$creditType=CreditType();
		//p($nftInfo);
		return view('', [
			'taskClass' => $taskClass,
			'userLevel' => $userLevel,
			'taskModle'	=> $taskModle,
			'nftInfo' => $nftInfo,
			'creditType' => $creditType
		]);
	}

	/**
	 * 编辑项目
	 * @return [type] [description]
	 */
	public function taskEdit(){
		if (request()->isAjax()) return model('Task')->edit();

		$id                       = input('get.id/d');
		$data                     = model('Task')->where('id', $id)->find();
		$data['end_time']         = ($data['end_time']) ? date('Y-m-d', $data['end_time']) : '';
		$data['finish_condition'] = json_decode($data['finish_condition'], true);

		if($data['examine_demo']){
			$data['examine_demo'] 	  = json_decode($data['examine_demo'], true);
		}else{
			$data['examine_demo'] 	  = array();
		}
		if($data['task_step']){
			$data['task_step']        = json_decode($data['task_step'], true);
		}else{
			$data['task_step']		  =	array();
		}

		$taskClass                = model('TaskClass')->select()->toArray();
		$userLevel                = model('UserGrade')->where('lang','en')->select()->toArray();

		$taskModle 				  = model('taskModel')->select()->toArray();


		$nftInfo=db('nft')->alias('a')->field('a.*,b.username')->join('users b','a.uid=b.id','left')->where(['a.id'=>$data['nft_id']])->find();
		$creditType=CreditType();
		return view('', [
			'data'      => $data,
			'taskClass' => $taskClass,
			'userLevel' => $userLevel,
			'taskModle'	=> $taskModle,
			'nftInfo' => $nftInfo,
			'creditType' => $creditType
		]);
	}

	/**
	 * 删除项目
	 * @return [type] [description]
	 */
	public function taskDel(){
		return model('Task')->del();
	}

	public function projectRecommend(){
		if(!request()->isAjax()) return '非法提交';
		$param = input('post.');//获取参数
		if(!$param) return '提交失败';
		//更新
		$updateRes = model('Project')->where('id',$param['id'])->setField('recommend',$param['val']);
		if(!$updateRes) return '修改失败';
		//添加操作日志
		$actionStr = $param['val']==2 ? '非' : '';
		$title = model('Project')->where('id',$param['id'])->value('title');
		model('Actionlog')->actionLog(session('manage_username'),'将项目'.$title.'设为'.$actionStr.'推荐',1);

		return 1;
	}

	/**
	 * 项目类型
	 * @return [type] [description]
	 */
	public function taskclass(){
		if (request()->isAjax()) {
			$param = input('post.');

			$count              = model('TaskClass')->count(); // 总记录数
			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'id';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('TaskClass')->order($param['sortField'], $param['sortType'])->limit($limitOffset, $param['limit'])->select()->toArray();
			foreach ($data as $key => &$value) {
				$value['stateStr'] = config('custom.taskclassstate')[$value['state']];
				$value['language'] = config('custom.lang')[$value['lang']];
				$value['bindType'] = config('custom.taskTypeBindType')[$value['bind_type']];
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $count,
				'data'  => $data
			]);
		}

		return view('task_class');
	}

	/**
	 * 添加类型
	 * @return [type] [description]
	 */
	public function TaskClassAdd(){
		if (request()->isAjax()) return model('TaskClass')->TaskClassAdd();

		return view();
	}

	/**
	 * 编辑类型
	 * @return [type] [description]
	 */
	public function TaskClassEdit(){
		if (request()->isAjax()) return model('TaskClass')->TaskClassEdit();

		$id = input('get.id/d');
		$data = model('TaskClass')->where('id', $id)->find();

		return view('', [
			'data'        => $data
		]);
	}

	/**
	 * 删除类型
	 * @return [type] [description]
	 */
	public function TaskClassDel(){
		return model('TaskClass')->TaskClassDel();
	}

	/**
	 * 返还方式
	 * @return [type] [description]
	 */
	public function returnType(){
		if (request()->isAjax()) {
			$param = input('post.');

			$count              = model('RepaymentMethod')->count(); // 总记录数
			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'id';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('RepaymentMethod')->order($param['sortField'], $param['sortType'])->limit($limitOffset, $param['limit'])->select()->toArray();
			foreach ($data as $key => &$value) {
				$value['stateStr'] = ($value['state'] == 1) ? '开启' : '关闭';
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $count,
				'data'  => $data
			]);
		}

		return view();
	}

	/**
	 * 添加方式
	 * @return [type] [description]
	 */
	public function returnTypeAdd(){
		if (request()->isAjax()) return model('RepaymentMethod')->projectTypeAdd();

		return view();
	}

	/**
	 * 编辑类型
	 * @return [type] [description]
	 */
	public function returnTypeEdit(){
		if (request()->isAjax()) return model('RepaymentMethod')->projectTypeEdit();

		$id = input('get.id/d');
		$data = model('RepaymentMethod')->where('id', $id)->find();

		return view('', [
			'data'        => $data
		]);
	}

	/**
	 * 删除方式
	 * @return [type] [description]
	 */
	public function returnTypeDel(){
		return model('RepaymentMethod')->projectTypeDel();
	}

	/**
	 * 投资记录
	 * @return [type] [description]
	 */
	public function investList(){
		if (request()->isAjax()) {
			$param = input('post.');
			//查询条件组装
			$where = array();

			// 用户名
			if(isset($param['username']) && $param['username']){
				$where[] = array('users.username','like','%'.$param['username'].'%');
			}
			// 项目
			if(isset($param['project']) && $param['project']){
				$where[] = array('pid','like','%'.$param['username'].'%');
			}
			// 推荐
			if(isset($param['state']) && $param['state']){
				$where[] = array('state','=',$param['state']);
			}
			// 时间
			if(isset($param['date_range']) && $param['date_range']){
				$dateTime = explode(' - ', $param['date_range']);
				$where[] = array('ly_order.add_time','>=',strtotime($dateTime[0]));
				$where[] = array('ly_order.add_time','<=',strtotime($dateTime[1]));
			}
			// else{
			// 	$todayStart = mktime(0,0,0,date('m'),date('d'),date('Y'));
			// 	$where[] = array('ly_order.add_time','>=',$todayStart);
			// 	$todayEnd = mktime(23,59,59,date('m'),date('d'),date('Y'));
			// 	$where[] = array('ly_order.add_time','<=',$todayEnd);
			// }

			$count              = model('Order')->join('project','ly_order.pid=project.id')->join('users','ly_order.uid=users.id')->count(); // 总记录数
			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'add_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('Order')
					->field('ly_order.*,project.title,users.username,phone')
					->join('project','ly_order.pid=project.id')
					->join('users','ly_order.uid=users.id')
					->where($where)->order($param['sortField'], $param['sortType'])->limit($limitOffset, $param['limit'])->select()->toArray();
			foreach ($data as $key => &$value) {
				switch ($value['state']) {
					case '1':
						$value['stateStr'] = '完成';
						break;
					case '2':
						$value['stateStr'] = '取消';
						break;
					default:
						$value['stateStr'] = '进行中';
						break;
				}
				$value['yieldRate']   = $value['daily_income'].' % + '.$value['rebate'].' %';
				$value['bearing_day'] = date('Y-m-d H:i:s', $value['bearing_day']);
				$value['due_day']     = date('Y-m-d H:i:s', $value['due_day']);
				$value['add_time']    = date('Y-m-d H:i:s', $value['add_time']);
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $count,
				'data'  => $data
			]);
		}

		return view();
	}

	/**
	 * 记录详情
	 * @return [type] [description]
	 */
	public function investDetails(){

	}

	/**
	 * 查看合同
	 * @return [type] [description]
	 */
	public function investPact(){
		if (request()->isAjax()) return model('Order')->investPact();

		$id = input('get.id/d');
		$data = model('Order')->where('id', $id)->find()->toArray();

		return view('', [
			'data' => $data
		]);
	}

	//撤销任务
	public function revokeTask(){

		$param			= input('post.');

		$id				= (input('post.id')) ? input('post.id') : 0;	// 任务ID;

		$lang			= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		if(!$id){
			return '参数错误';
		}

		$info = model('task')->where(array(['id','=',$id]))->find();

		if(!$info){
			return config($lang.'.lang')[41];
		}
		if(!in_array($info['status'],[1,2])){
			return '订单状态错误';
		}

		$is_up	=	model('task')->where(array(['id','=',$id]))->update(array('status'=>4));//撤销

		if(!$is_up){
			return config($lang.'.lang')[41];
		}
		//卖出订单  把数量重新入到客户碎片表
		if($info['task_type']==1){
			db('users_goods')->where(['nft_id'=>$info['nft_id'],'uid'=>$info['uid']])->setInc('available_number', $info['surplus_number']);
		}

		// $userBalance_p		= 	model('UserTotal')->where('uid', $uid)->value('balance');	// 获取用户的余额

		// $total_price		=	$info['total_price']	+	$info['task_pump'];

		// $is_up_to = model('UserTotal')->where('uid', $uid)->setInc('balance', $total_price);
		// if(!$is_up_to){

		// 	$this->where(array(['id','=',$id],['uid','=',$uid],['status','=',5]))->update(array('status'=>1));//撤销
		// 	return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		// }

		// 流水

		// $financial_data_p['uid'] 					= $uid;
		// $financial_data_p['username'] 				= $username;
		// $financial_data_p['order_number'] 			= $info['order_number'];
		// $financial_data_p['trade_number'] 			= 'L'.trading_number();;
		// $financial_data_p['trade_type'] 			= 10;
		// $financial_data_p['trade_before_balance']	= $userBalance_p;
		// $financial_data_p['trade_amount'] 			= $total_price;
		// $financial_data_p['account_balance'] 		= $userBalance_p + $total_price;
		// $financial_data_p['remarks'] 				= config($lang.'.lang')[159];
		// $financial_data_p['types'] 					= 1;	// 用户1，商户2

		// model('common/TradeDetails')->tradeDetails($financial_data_p);

		return 1;
	}

	/**
	 * 任务列表
	 * @return [type] [description]
	 */
	public function taskList(){
		$statusArr=$this->getTaskStatus();
		if (request()->isAjax()) {
			$param = input('param.');

			//查询条件初始化
			$where = array();
			// 标题
			if(isset($param['username']) && $param['username']){
				$where[] = array(['u.username','=',$param['username']]);
			}

			// 标题
			if(isset($param['title']) && $param['title']){
				$where[] = array('title','like','%'.$param['title'].'%');
			}

			// 状态
			if(isset($param['status']) && $param['status']){
				$where[] = array(['a.status','=',$param['status']]);
			}

			// 类型
			if(isset($param['task_type']) && $param['task_type']){
				$where[] = array('task_type','=',$param['task_type']);
			}
			// 分类
			if(isset($param['task_class']) && $param['task_class']){
				$where[] = array('task_class','=',$param['task_class']);
			}
            // 语言
            if(isset($param['lang']) && $param['lang']){
                $where[] = array('ly_task.lang','=',$param['lang']);
            }
			// 时间
			if(isset($param['datetime_range']) && $param['datetime_range']){
				$dateTime = explode(' - ', $param['datetime_range']);
				$where[] = ['n.create_time', 'between time', [$dateTime[0], $dateTime[1]]];
			}
            /*else{
				$todayStart = mktime(0,0,0,date('m'),date('d'),date('Y')) - 30 * 86400;
				$todayEnd = mktime(23,59,59,date('m'),date('d'),date('Y'));
				$where[] = ['add_time', 'between time', [$todayStart, $todayEnd]];
			}*/

			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 10; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'add_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';
			$taksType = config('custom.taskType');//账号状态
			//查询符合条件的数据
			$data = model('api/Task')
                ->field('ly_task.*,ly_task_class.group_name,n.name as nname,n.file as nfile,n.create_time as ncreate_time,u.username as uusername,u.nickname ')
                ->alias('a')
                ->join('ly_task_class','ly_task.task_class=ly_task_class.id','left')
                ->join('nft n','a.nft_id=n.id','left')
                ->join('users u','a.uid=u.id','left')
                ->where($where)
                ->where('a.nft_id != 0')
                ->order($param['sortField'], $param['sortType'])
                ->paginate(10)
                ->toArray();

            $t 					= time();
            $end_time			= mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
            $creditType=CreditType();
            foreach ($data['data'] as $key => &$value) {
//
                $value['statusStr']=isset($statusArr[$value['status']])?$statusArr[$value['status']]:'未知';
                 if($value['end_time'] < $end_time){
                 	$value['revoke']	=	1;
                 }else{
                 	$value['revoke']	=	0;
                 }
                $value['task_type_str']   		= config('custom.taskType')[$value['task_type']];
                $value['speed']           		= $value['receive_number'].'/'.$value['total_number'];
                if($value['task_pump']){
                    $value['speed_total_price']     = $value['total_price'].'+'.$value['task_pump'];
                }else{
                    $value['speed_total_price']     = $value['total_price'];
                }
                if($value['username']){
                    $value['username']     = $value['username'];
                }else{
                    $value['username']     = '管理员';
                }
                $value['format_complete_time'] 		= ($value['complete_time']) ? date('Y-m-d', $value['complete_time']) : '';
                $value['format_add_time'] 		= ($value['add_time']) ? date('Y-m-d H:i:s', $value['add_time']) : '';
                $value['format_end_time'] 		= ($value['end_time']) ? date('Y-m-d H:i:s', $value['end_time']) : '';
                $value['ncreate_time'] 		= ($value['ncreate_time']) ? date('Y-m-d', $value['ncreate_time']) : '';
//                $value['language'] = config('custom.lang')[$value['lang']];
//
                $file=$value['nfile']?explode(',',$value['nfile']):[];
                $file_img='';
                foreach($file as $k=>$v){
                    $file_img.=" <div class='layer-photos-demo'><img layer-pid='' layer-src='{$v}' src='{$v}' alt='文件' style='width:60px;height:60px';></div>";
                }
                $value['nfile_img']=$file_img;

                $value['credit_type_str']= getCreditTypeName($value['credit_type']);
            }

            return json([
                'code'  => 0,
                'msg'   => '',
                'count' => $data['total'],
                'data'  => $data['data']
            ]);
		}

		$taskClass = array();
		$this->assign('statusArr','');
		return view('', [
			'taskClass' => $taskClass
		]);
	}
	/**
	 * Undocumented function
	 *
	 * @return void
	 */
	private function getTaskStatus(){
		return [
			1=>'预售中',
			2=>'进行中',
			3=>'已结束',
			4=>'已撤回',
		];
	}

	/**
	 * 任务审核
	 * @return [type] [description]
	 */
	public function taskAudit(){
		if (request()->isAjax()) return model('Task')->audit();

		$id                       = input('get.id/d');

		$data                     = model('Task')->where('id', $id)->find();
		//$data['end_time']         = ($data['end_time']) ? date('Y-m-d', $data['end_time']) : '';
		//$data['finish_condition'] = json_decode($data['finish_condition'], true);
		//$data['task_step']        	= json_decode($data['task_step'], true);

		if($data['examine_demo']){
			$data['examine_demo']   = json_decode($data['examine_demo'], true);
		}else{
			$data['examine_demo']	=	array();
		}

		$t 					= time();
		$end_time			= mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
		$data['revoke']		= 0;//撤销
		if($data['end_time'] < $end_time){
			$data['revoke']	=	1;
		}

		$data['statusStr']			= config('custom.taskStatus')[$data['status']];
		//$taskClass                = model('TaskClass')->select()->toArray();

		return view('', [
			'data'      => $data,
			//'taskClass' => $taskClass
		]);
	}

    protected function userTaskInfo(&$value){
        $usertasksStatus = config('custom.usertaskStatus');
        $userTaskTypes = config('custom.userTaskType');
        $value['statusStr']      =  $usertasksStatus[$value['status']];
        $value['userTaskTypeStr'] = $userTaskTypes[$value['user_task_type']];
        $value['add_time'] 		 = ($value['add_time']) ? date('Y-m-d H:i:s', $value['add_time']) : '';//接单时间
        $file=$value['nfile']?explode(',',$value['nfile']):[];
        $file_img='';
        foreach($file as $v){
            $file_img.=" <div class='layer-photos-demo'><img layer-pid='' layer-src='{$v}' src='{$v}' alt='文件' style='width:60px;height:60px';></div>";
        }
        $value['nfile_img']=$file_img;
        $value['nfile_img_url']= $value['nfile'];
        $screen = $value['screenshots']?explode(',',$value['screenshots']):[];
        $screen_img = '';
        foreach($screen as $v){
            $screen_img.=" <div class='layer-photos-demo'><img layer-pid='' layer-src='{$v}' src='{$v}' alt='文件' style='width:60px;height:60px';></div>";
        }
        $value['screen_img']=$screen_img;
        $value['screenshots']=$screen;
        if($value['user_task_type']==2){
            $value['buyusername']=$value['username'];
            $value['saleusername']=$value['susername'];
        }
        if($value['user_task_type']==1){
            $value['buyusername']=$value['susername'];
            $value['saleusername']=$value['username'];
        }
        $value['credit_type_str']= $value['credit_type'];
    }
	/**
	 * 任务记录
	 * @return [type] [description]
	 */
	public function userTaskList(){
		$statusArr=$this->getTaskStatus();
		$param = input('param.');
		$username='';
        if(isset($param['uid'])&&!empty($param['uid'])){
            $username=db('users')->where(['id'=>$param['uid']])->value('username');
        }
		if (request()->isAjax()) {

			

			//查询条件初始化
			$where = array();

			// 用户名
			if(isset($param['username']) && $param['username']){
				$where[] = array(['ly_user_task.username','=',$param['username']]);
			}

<<<<<<< HEAD

            if(isset($param['account_type']) && $param['account_type']>0){
                $where[] = array(['account_type','=',$param['account_type']]);
            }

            if(isset($param['task_type']) && $param['task_type']>0){
                $where[] = array(['task_type','=',$param['task_type']]);
            }

            if(isset($param['order_sn']) && strlen($param['order_sn'])>0){
                $where[] = array(['order_sn','=',$param['order_sn']]);
            }

            // 状态
=======
			
			// 状态
>>>>>>> d5744068e96ec6af195a083b33e0e08e138eee33
			if(isset($param['status']) && $param['status']){
				$where[] = array(['ly_user_task.status','=',$param['status']]);
			}

			// 时间
			if(isset($param['datetime_range']) && $param['datetime_range']){
				$dateTime = explode(' - ', $param['datetime_range']);
				$where[] = ['ly_user_task.add_time', 'between time', [$dateTime[0], $dateTime[1]]];
			}else{
				// $todayStart = mktime(0,0,0,date('m'),date('d'),date('Y'));
				// $todayEnd = mktime(23,59,59,date('m'),date('d'),date('Y'));
				// $where[] = ['ly_user_task.add_time', 'between time', [$todayStart, $todayEnd]];
			}

            $where[] = array(['ly_user_task.status','>',0]);

			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 10; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'add_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('UserTask')->field('ly_task.title,ly_task.nft_id,ly_task.credit_type,ly_user_task.*,ly_users.username as susername,ly_nft.name as nname,ly_nft.file as nfile')
			->join('ly_task','ly_task.id=ly_user_task.task_id','left')
			->join('ly_users','ly_user_task.fuid=ly_users.id','left')
			->join('ly_nft','ly_task.nft_id=ly_nft.id','left')
			->where($where)
			->order($param['sortField'], $param['sortType'])
			->paginate($param['limit'])
			->toArray();


            $usertasksStatus = config('custom.usertaskStatus');
            $userTaskTypes = config('custom.userTaskType');
			foreach ($data['data'] as $key => &$value) {
                $this->userTaskInfo($value);
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $data['total'],
				'data'  => $data['data']
			]);
		}
		$this->assign('username',$username);
		return view('');
	}


	/**
	 * 任务记录审核
	 * @return [type] [description]
	 */
	public function userTaskAudit(){
		if (request()->isAjax())	return model('Task')->userTaskAudit();

		$id                       	= input('get.id/d');

		$data                     	= model('UserTask')->field('ly_user_task.*,ly_task.title')->join('ly_task','ly_task.id=ly_user_task.task_id')->where(array(['ly_user_task.id','=',$id]))->find();

        $usertasksStatus = config('custom.usertaskStatus');
		$data['statusStr']			= $usertasksStatus[$data['status']];
        $userTaskTypes = config('custom.userTaskType');
        $data['typeStr']			= $userTaskTypes[$data['user_task_type']];

		return view('', [
			'data'      => $data,
		]);
	}

	/**
	 * 订单编辑
	 * @return [type] [description]
	 */
	public function userTaskEdit(){
		if (request()->isAjax()) return model('Task')->edit();

		$id                       = input('get.id/d');

        $data = model('UserTask')->field('ly_task.title,ly_task.nft_id,ly_task.credit_type,ly_user_task.*,ly_users.username as susername,ly_nft.name as nname,ly_nft.file as nfile')
            ->join('ly_task','ly_task.id=ly_user_task.task_id','left')
            ->join('ly_users','ly_user_task.fuid=ly_users.id','left')
            ->join('ly_nft','ly_task.nft_id=ly_nft.id','left')
            ->where(array(['ly_user_task.id','=',$id]))
            ->find();

        $this->userTaskInfo($data);

		return view('', [
			'data'      => $data,
		]);
	}

    public function userTaskDel(){
        return model('Users')->softDel();
    }

	/**
	 * 任务记录
	 * @return [type] [description]
	 */
	public function taskModelList(){
		if (request()->isAjax()) {

			$param = input('param.');

			//查询条件初始化
			$where = array();

			// 模板名字
			if(isset($param['name']) && $param['name']){
				$where[] = array(['name','=',$param['name']]);
			}

			// 任务标题
			if(isset($param['title']) && $param['title']){
				$where[] = array(['title','=',$param['title']]);
			}

			$count = model('TaskModel')->where($where)->count(); // 总记录数


			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 10; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'add_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
			$data = model('TaskModel')->where($where)->order($param['sortField'], $param['sortType'])->limit($limitOffset, $param['limit'])->select()->toArray();

			foreach ($data as $key => &$value) {
				$value['format_add_time'] 		 = ($value['add_time']) ? date('Y-m-d H:i:s', $value['add_time']) : '';//接单时间
				$value['class_name'] 			 = model('TaskClass')->where('id',$value['task_class'])->value('h_group_name');//接单时间
			}

			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $count,
				'data'  => $data
			]);
		}

		return view('');
	}
	//添加模板
	public function taskModelAdd(){
		if (request()->isAjax()) return model('taskModel')->add();
		$userLevel = model('UserGrade')->where('lang','en')->select()->toArray();
		$taskClass                = model('TaskClass')->select()->toArray();

		return view('', [
			'taskClass' => $taskClass,
			'userLevel' => $userLevel
		]);
	}
	/**
	 * 编辑项目
	 * @return [type] [description]
	 */
	public function taskModelEdit(){

		if (request()->isAjax()) return model('taskModel')->edit();

		$id                       = input('get.id/d');
		$data                     = model('taskModel')->where('id', $id)->find();
		$data['end_time']         = ($data['end_time']) ? date('Y-m-d', $data['end_time']) : '';


		$data['finish_condition'] = json_decode($data['finish_condition'], true);
		if($data['examine_demo']){
			$data['examine_demo'] 	  = json_decode($data['examine_demo'], true);
		}else{
			$data['examine_demo'] 	  = array();
		}
		if($data['task_step']){
			$data['task_step']        = json_decode($data['task_step'], true);
		}else{
			$data['task_step']		  =	array();
		}

		$userLevel                = model('UserGrade')->where('lang','en')->select()->toArray();

		$taskClass                = model('TaskClass')->select()->toArray();

		return view('', [
			'data'      => $data,
			'taskClass' => $taskClass,
			'userLevel' => $userLevel
		]);
	}

	/**
	 * 删除项目
	 * @return [type] [description]
	 */
	public function taskModelDel(){
		return model('taskModel')->del();
	}


}
